package com.beiing.tianshuai.tianshuai.dongtai.ui;


import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.CommentNotice_RVAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.dongtai.DynamicRelayDetailActivity;
import com.beiing.tianshuai.tianshuai.dongtai.view.DynamicDetailActivity;
import com.beiing.tianshuai.tianshuai.entity.ConsumeMarksBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicCommentNoticeBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.rx.MsgEvent;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomEmptyLayout;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 * Create by Jinni 2017-11-27
 * Describe:"展示动态评论消息的Fragment"
 */
public class DynamicReplyMessageFragment extends BaseFragment {

    @BindView(R.id.refresh_header)
    MyRefreshHeader mRefreshHeader;
    @BindView(R.id.rcv_dynamic_reply_message)
    RecyclerView mRcvDynamicReplyMessage;
    @BindView(R.id.refresh_footer)
    ClassicsFooter mRefreshFooter;
    @BindView(R.id.smart_refreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;
    @BindView(R.id.empty_view)
    CustomEmptyLayout mEmptyLayout;

    /**
     * 当前登录用户的id
     */
    private String mUid;

    /**
     * 请求更多数据的起始位置
     */
    private int firstRow = 0;

    /**
     * 请求更多数据的条目数量
     */
    private int listRows = 20;

    /**
     * 是否加载所有数据
     */
    private boolean isLoadFinish;

    /**
     * 是否加载过一次
     */
    private boolean isLoaded;

    /**
     * 数据源
     */
    private ArrayList<DynamicCommentNoticeBean.DataBean.NumberBean> mNoticeList;

    /**
     * 网络请求回的部分数据源
     */
    private List<DynamicCommentNoticeBean.DataBean.NumberBean> numberBeanList;

    /**
     * 数据源适配器
     */
    private CommentNotice_RVAdapter mAdapter;

    /**
     * 网络重新连接次数 避免超时现象
     */
    private int retryCount = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dynamic_reply;
    }

    @Override
    protected void init(View view) {
        mUid = UserInfoBean.getUid(mContext);
        initRecyclerView();
        initListener();
        loadData(mUid, firstRow, listRows);
        consumeMarks(mUid);
    }

    private void initListener() {
        //下拉刷新、上拉加载的监听
        mSmartRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mSmartRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        mSmartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinish) {
                    loadData(mUid, firstRow, listRows);
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                isLoadFinish = false;
                mNoticeList.clear();
                firstRow = 0;
                loadData(mUid, firstRow, listRows);
            }
        });
    }

    private void initRecyclerView() {
        mNoticeList = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRcvDynamicReplyMessage.setLayoutManager(manager);
        //绘制item间的分割线，
        mRcvDynamicReplyMessage.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                        ContextCompat.getColor(mContext, R.color.common_gray_background))
        );
        mAdapter = new CommentNotice_RVAdapter(mContext, mNoticeList);
        mRcvDynamicReplyMessage.setAdapter(mAdapter);

        mAdapter.setOnAvatarClickListener(new CommentNotice_RVAdapter.OnAvatarClickListener() {
            @Override
            public void onAvatarClick(View view, int position) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", mNoticeList.get(position).getUid());
                startActivity(intent);
            }
        });

        mAdapter.setOnItemClickListener(new CommentNotice_RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                switch (mNoticeList.get(position).getTableType()) {
                    case "0":       //原动态评论
                        intent.setClass(mContext, DynamicDetailActivity.class);
                        break;
                    case "1":       //转发动态评论
                        intent.setClass(mContext, DynamicRelayDetailActivity.class);
                        break;
                    case "2":       //原动态回复
                        intent.setClass(mContext, DynamicDetailActivity.class);
                        break;
                    case "3":       //转发动态回复
                        intent.setClass(mContext, DynamicRelayDetailActivity.class);
                        break;
                }
                intent.putExtra("dynamic_id", mNoticeList.get(position).getToId());
                startActivity(intent);
            }
        });

    }

    private void showCommentList(List<DynamicCommentNoticeBean.DataBean.NumberBean> numberBeanList) {
        if (mSmartRefreshLayout != null && (mSmartRefreshLayout.isRefreshing() || mSmartRefreshLayout.isLoading())) {
            mSmartRefreshLayout.finishRefresh();
            mSmartRefreshLayout.finishLoadmore();
        }
        int size = numberBeanList.size();
        if (size == 0) {
            if (mNoticeList.isEmpty()) {
                mEmptyLayout.setEmptyView(R.drawable.bg_empty_warning, "空空的");
            }
            isLoadFinish = true;
//            mSmartRefreshLayout.setLoadmoreFinished(true);
        } else if (size < listRows) {
            isLoadFinish = false;
            firstRow += size;
//            mSmartRefreshLayout.setLoadmoreFinished(false);
        } else {
            isLoadFinish = false;
            firstRow += size;
//            mSmartRefreshLayout.setLoadmoreFinished(false);
        }
        mNoticeList.addAll(numberBeanList);
        mAdapter.notifyDataSetChanged();
    }

    private void loadData(final String uid, final int firstRow, final int listRows) {
        showProgress();
        DisposableObserver<DynamicCommentNoticeBean> observer = new DisposableObserver<DynamicCommentNoticeBean>() {
            @Override
            public void onNext(@NonNull DynamicCommentNoticeBean dynamicCommentNoticeBean) {
                isLoaded = true;
                hideProgress();
                numberBeanList = dynamicCommentNoticeBean.getData().getNumber();
                showCommentList(numberBeanList);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                if (retryCount < 5) {
                    retryCount++;
                    loadData(uid, firstRow, listRows);
                } else {
                    retryCount = 0;
                    showShortText("请求失败");
                    if (mSmartRefreshLayout.isRefreshing()) {
                        mSmartRefreshLayout.finishRefresh(false);
                    }
                    if (mSmartRefreshLayout.isLoading()) {
                        mSmartRefreshLayout.finishLoadmore(false);
                    }
                    LogUtils.e("获取评论数据失败 " + e.toString(), "DynamicReplyMsg");
                }
            }

            @Override
            public void onComplete() {
                LogUtils.i("获取评论数据完成", "DynamicReplyMsg");
            }
        };

        DataManager.getDynamicCommentNoticeResult(uid, firstRow, listRows)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private void consumeMarks(String uid) {
        DisposableObserver<ConsumeMarksBean> observer = new DisposableObserver<ConsumeMarksBean>() {
            @Override
            public void onNext(@NonNull ConsumeMarksBean consumeMarksBean) {
                RxBus.getInstanceBus().post(new MsgEvent<>("清除评论"));
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

        DataManager.getConsumeCommentMarksResult(uid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private void showProgress() {
        if (mSmartRefreshLayout != null && !mSmartRefreshLayout.isLoading() && !mSmartRefreshLayout.isRefreshing()) {
            mEmptyLayout.setInProgress();
        }
    }

    private void hideProgress() {
        if (mEmptyLayout != null) {
            mEmptyLayout.setChildrenVisible();
        }
    }
}
